package com.hycloud.cloudstack.resource;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.hycloud.cloudstack.common.CloudstackApi;
import com.hycloud.cloudstack.common.WebUtils;
import com.hycloud.cloudstack.model.Host;
import com.hycloud.cloudstack.service.HostService;

@RestController
@RequestMapping("/host")
public class HostResource {
	
	Logger log =LoggerFactory.getLogger(HostResource.class);
	
	@Autowired
	private CloudstackApi cloudstackApi;
	
	@Autowired
	private HostService hostService;
	
	@RequestMapping(method=RequestMethod.GET)
	@CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = { "x-auth-token", "x-requested-with" })
	public ResponseEntity<String> listHosts(HttpServletRequest request){
		try {
			Map<String, String> params = WebUtils.getParameterAsMap(request);
			String result = cloudstackApi.api(params);
			return ResponseEntity.status(HttpStatus.OK).body(result);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}
	
	@RequestMapping(method=RequestMethod.POST)
	@CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = { "x-auth-token", "x-requested-with" })
	public ResponseEntity<Host> savetHosts(com.hycloud.cloudstack.model.Host host){
		try {
			hostService.create(host);
			return ResponseEntity.status(HttpStatus.OK).body(host);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}
}
